package com.dhms.vostok1.utils

import android.annotation.SuppressLint
import android.icu.text.SimpleDateFormat

import android.net.Uri
import com.dhms.uikit.PdfViewerActivity
import com.dhms.vostok1.service.net.NetworkApi
import retrofit2.Retrofit
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.util.zip.GZIPOutputStream
import kotlin.math.ceil

class Utils {
    companion object {
        private val HEX = "0123456789ABCDEF".toCharArray()
        const val deviceId = "deviceid"

        @JvmStatic
        @SuppressLint("NewApi", "SimpleDateFormat")
        fun parseDateString(timeStamp: Long, pattern: String = "yyyy-MM-dd HH:mm:ss"): String? {
            val format = SimpleDateFormat(pattern)

            return format.format(timeStamp * 1000L)
        }

        @JvmStatic
        @SuppressLint("NewApi", "SimpleDateFormat")
        fun parseTimeout(time: String): Int {
            val timeStamp = time.toDate()?.secondTimeStamp()
            return if (timeStamp != null) {
                val currentTime = System.currentTimeMillis() / 1000
                val timeout = ceil(((timeStamp - currentTime) / 60).toDouble()).toInt()
                if (timeout > 60 || timeout <= 0) {
                    -1
                } else {
                    timeout
                }
            } else {
                -1
            }
        }

        @JvmStatic
        fun parseProductId(macAddress: String): String {
            return macAddress.replace(":", "").substring(4)
        }

        @JvmStatic
        fun parseAddress(url: String): String {
            return if (url.startsWith("http")) {
                url
            } else {
                NetworkApi.baseUrl + url
            }
        }

        @JvmStatic
        fun gzip(content: ByteArray): ByteArray? {
            val baos = ByteArrayOutputStream()
            var gzip: GZIPOutputStream? = null
            var result: ByteArray? = null
            try {
                gzip = GZIPOutputStream(baos)
                gzip.write(content)
                gzip.flush()
                gzip.close()
                result = baos.toByteArray()
            } catch (ex: IOException) {
                result = null
            } finally {
                try {
                    gzip?.close()
                } catch (err: IOException) {
                    result = null
                }
            }
            return result
        }

        @JvmStatic
        fun parseOssUrl(url: String): String {
            return if (url.startsWith("http")) {
                url
            } else {
                NetworkApi.baseUrl + url
            }
        }

        @JvmStatic
        fun toHexString(bytes: ByteArray): String {
            if (bytes.isEmpty()) {
                return ""
            }
            val hexChars = CharArray(bytes.size * 2)
            for (j in bytes.indices) {
                val v = (bytes[j].toInt() and 0xFF)
                hexChars[j * 2] = HEX[v ushr 4]
                hexChars[j * 2 + 1] = HEX[v and 0x0F]
            }
            return String(hexChars)
        }

        @JvmStatic
        fun dhmsSpcDeviceBatteryLevel(voltage: Float): Float {
            var batteryLevel = 0.0f
            if (voltage >= 4.0f) {
                batteryLevel = 1.0f
            } else if (voltage >= 3.83f) {
                batteryLevel = 0.8f
            } else if (voltage >= 3.67f) {
                batteryLevel = 0.6f
            } else if (voltage >= 3.6f) {
                batteryLevel = 0.4f
            } else if (voltage >= 3.53f) {
                batteryLevel = 0.2f
            } else if (voltage >= 3.45f) {
                batteryLevel = 0.1f
            } else if (voltage >= 3.37f) {
                batteryLevel = 0.05f
            }
            return batteryLevel
        }

        @JvmStatic
        suspend fun downloadFile(
            url: String,
            filePath: String,
            onFileDownloaded: (file: File?) -> Unit,
        ) {
            try {
                val fileName = url.split("/").last().split("?").first()
                val body =
                    Retrofit.Builder()
                        .baseUrl(NetworkApi.baseUrl!!)
                        .build().create(PdfViewerActivity.Companion.NetworkService::class.java)
                        .downloadFile(url)
                Thread {
                    val file = File(filePath, fileName)
                    val fileOutputStream = FileOutputStream(file)
                    fileOutputStream.write(body.bytes())
                    fileOutputStream.close()
                    onFileDownloaded(File(filePath, fileName))
                }.start()
            } catch (e: Exception) {
                e.printStackTrace()
                onFileDownloaded(null)
            }
        }


        @JvmStatic
        fun getPercentage(number1: Int?, number2: Int?): Int {
            val v = (number1?.toFloat() ?: 0f) / (number2?.toFloat() ?: 1f) * 100
            return v.toInt()
        }

        fun getQueryParameter(url: String, key: String): String? {
            val uri: Uri = Uri.parse(url)
            return uri.getQueryParameter(key)

        }
    }
}